package com.java.architect.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;

import java.io.Serializable;

/**
 * 空对象，只用于数据取到null时在缓存内同步标记
 *
 * @author Java架构师之旅
 * @since 2020/11/25
 */
@Data
public class NullObject implements Serializable {
    private static final String NULL_OBJ = "$NullObject$";

    private static final long serialVersionUID = 1L;

    String nullObj;
    Long timestamp;

    public NullObject() {
        this.nullObj = NULL_OBJ;
        this.timestamp = System.currentTimeMillis();
    }

    public static boolean isNullObject(String str) {
        Object obj = JSON.parse(str);
        return (obj instanceof JSONObject) && (((JSONObject) obj).containsKey("nullObj")) && (((JSONObject) obj).getString("nullObj").equals(NULL_OBJ));
    }

    public static boolean isNullObject(Object obj) {
        return obj instanceof NullObject;
    }

    public static boolean isExpire(NullObject obj, int expireSecond) {
        return System.currentTimeMillis() - obj.getTimestamp() > expireSecond * 1000;
    }

    public static boolean isNotExpireNullObject(Object obj, int expireSecond) {
        return isNullObject(obj) && !isExpire((NullObject) obj, expireSecond);
    }

    public static boolean isExpireNullObject(Object obj, int expireSecond) {
        return isNullObject(obj) && isExpire((NullObject) obj, expireSecond);
    }
}
